<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://chenjiabing666.github.io/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="code-ltfpVmGDr3" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring Boot," />





  <link rel="alternate" href="/atom.xml" title="不才陈某技术博客" type="application/atom+xml" />






<meta name="description" content="前言大约在19年的这个时候，老同事公司在做医疗系统，需要和HIS系统对接一些信息，比如患者、医护、医嘱、科室等信息。但是起初并不知道如何与HIS无缝对接，于是向我取经。
最终经过讨论采用了视图对接的方式，大致就是HIS系统提供视图，他们进行对接。">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot 与多数据源的那点事儿~">
<meta property="og:url" content="https://chenjiabing666.github.io/2020/10/21/SpringBoot与多数据源的那点事儿/index.html">
<meta property="og:site_name" content="不才陈某技术博客">
<meta property="og:description" content="前言大约在19年的这个时候，老同事公司在做医疗系统，需要和HIS系统对接一些信息，比如患者、医护、医嘱、科室等信息。但是起初并不知道如何与HIS无缝对接，于是向我取经。
最终经过讨论采用了视图对接的方式，大致就是HIS系统提供视图，他们进行对接。">
<meta property="og:image" content="https://gitee.com/chenjiabing666/BlogImage/raw/master/Spring%20Boot%E7%AC%AC%E5%8D%81%E4%B8%89%E5%BC%B9%EF%BC%8C%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90%E6%95%B4%E5%90%88/1.jpg">
<meta property="og:image" content="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png">
<meta property="og:updated_time" content="2020-10-22T13:12:13.784Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Boot 与多数据源的那点事儿~">
<meta name="twitter:description" content="前言大约在19年的这个时候，老同事公司在做医疗系统，需要和HIS系统对接一些信息，比如患者、医护、医嘱、科室等信息。但是起初并不知道如何与HIS无缝对接，于是向我取经。
最终经过讨论采用了视图对接的方式，大致就是HIS系统提供视图，他们进行对接。">
<meta name="twitter:image" content="https://gitee.com/chenjiabing666/BlogImage/raw/master/Spring%20Boot%E7%AC%AC%E5%8D%81%E4%B8%89%E5%BC%B9%EF%BC%8C%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90%E6%95%B4%E5%90%88/1.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenjiabing666.github.io/2020/10/21/SpringBoot与多数据源的那点事儿/"/>





  <title>Spring Boot 与多数据源的那点事儿~ | 不才陈某技术博客</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不才陈某技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信公众号：码猿技术专栏</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenjiabing666.github.io/2020/10/21/SpringBoot与多数据源的那点事儿/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="不才陈某">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不才陈某技术博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring Boot 与多数据源的那点事儿~</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-21T16:44:24+08:00">
                2020-10-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring-Boot-进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Spring Boot 进阶</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/10/21/SpringBoot与多数据源的那点事儿/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/10/21/SpringBoot与多数据源的那点事儿/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
		  
		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
			

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  16
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>大约在19年的这个时候，老同事公司在做医疗系统，需要和<code>HIS</code>系统对接一些信息，比如患者、医护、医嘱、科室等信息。但是起初并不知道如何与HIS无缝对接，于是向我取经。</p>
<p>最终经过讨论采用了<code>视图对接</code>的方式，大致就是HIS系统提供视图，他们进行对接。</p>
<a id="more"></a>
<h2 id="写这篇文章的目的"><a href="#写这篇文章的目的" class="headerlink" title="写这篇文章的目的"></a>写这篇文章的目的</h2><p>这篇文章将会涉及到Spring Boot 与Mybatis、数据库整合，类似于整合Mybatis与数据库的文章其实网上很多，作者此前也写过一篇文章详细的介绍了一些整合的套路：<a href="https://mp.weixin.qq.com/s/USXciK7mWB2-sud3-g19PA" target="_blank" rel="external">Spring Boot 整合多点套路，少走点弯路~</a>，有兴趣的可以看看。</p>
<h2 id="什么是多数据源？"><a href="#什么是多数据源？" class="headerlink" title="什么是多数据源？"></a>什么是多数据源？</h2><p>最常见的单一应用中最多涉及到一个数据库，即是一个数据源（<code>Datasource</code>）。那么顾名思义，多数据源就是在一个单一应用中涉及到了两个及以上的数据库了。</p>
<p>其实在配置数据源的时候就已经很明确这个定义了，如以下代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span>(name = <span class="string">"dataSource"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</div><div class="line">    DruidDataSource druidDataSource = <span class="keyword">new</span> DruidDataSource();</div><div class="line">    druidDataSource.setUrl(url);</div><div class="line">    druidDataSource.setUsername(username);</div><div class="line">    druidDataSource.setDriverClassName(driverClassName);</div><div class="line">    druidDataSource.setPassword(password);</div><div class="line">    <span class="keyword">return</span> druidDataSource;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>url</code>、<code>username</code>、<code>password</code>这三个属性已经唯一确定了一个数据库了，<code>DataSource</code>则是依赖这三个创建出来的。则多数据源即是配置多个<code>DataSource</code>（暂且这么理解）。</p>
</blockquote>
<h2 id="何时用到多数据源？"><a href="#何时用到多数据源？" class="headerlink" title="何时用到多数据源？"></a>何时用到多数据源？</h2><p>正如前言介绍到的一个场景，相信大多数做过医疗系统的都会和<code>HIS</code>打交道，为了简化护士以及医生的操作流程，必须要将必要的信息从<code>HIS</code>系统对接过来，据我了解的大致有两种方案如下：</p>
<ol>
<li><code>HIS</code>提供视图，比如医护视图、患者视图等，而此时其他系统只需要定时的从<code>HIS</code>视图中读取数据同步到自己数据库中即可。</li>
<li><code>HIS</code>提供接口，无论是<code>webService</code>还是<code>HTTP</code>形式都是可行的，此时其他系统只需要按照要求调接口即可。</li>
</ol>
<blockquote>
<p>很明显第一种方案涉及到了至少两个数据库了，一个是<code>HIS</code>数据库，一个自己系统的数据库，在单一应用中必然需要用到<strong>多数据源的切换</strong>才能达到目的。</p>
</blockquote>
<p>当然多数据源的使用场景还是有很多的，以上只是简单的一个场景。</p>
<h2 id="整合单一的数据源"><a href="#整合单一的数据源" class="headerlink" title="整合单一的数据源"></a>整合单一的数据源</h2><p>本文使用阿里的数据库连接池<code>druid</code>，添加依赖如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!--druid连接池--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>druid-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.9<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>阿里的数据库连接池非常强大，比如<code>数据监控</code>、<code>数据库加密</code>等等内容，本文仅仅演示与Spring Boot整合的过程，一些其他的功能后续可以自己研究添加。</p>
<p>Druid连接池的<code>starter</code>的自动配置类是<code>DruidDataSourceAutoConfigure</code>，类上标注如下一行注解：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@EnableConfigurationProperties</span>(&#123;DruidStatProperties.class, DataSourceProperties.class&#125;)</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>@EnableConfigurationProperties</code>这个注解使得配置文件中的配置生效并且映射到指定类的属性。</p>
</blockquote>
<p><code>DruidStatProperties</code>中指定的前缀是<code>spring.datasource.druid</code>，这个配置主要是用来设置连接池的一些参数。</p>
<p><code>DataSourceProperties</code>中指定的前缀是<code>spring.datasource</code>，这个主要是用来设置数据库的<code>url</code>、<code>username</code>、<code>password</code>等信息。</p>
<p>因此我们只需要在全局配置文件中指定<strong>数据库的一些配置</strong>以及<strong>连接池的一些配置</strong>信息即可，前缀分别是<code>spring.datasource.druid</code>、<code>spring.datasource</code>，以下是个人随便配置的(<code>application.properties</code>)：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">spring.datasource.url=jdbc\:mysql\://120.26.101.xxx\:3306/xxx?useUnicode\=true&amp;characterEncoding\=UTF-8&amp;zeroDateTimeBehavior\=convertToNull&amp;useSSL\=false&amp;allowMultiQueries\=true&amp;serverTimezone=Asia/Shanghai</div><div class="line">spring.datasource.username=root</div><div class="line">spring.datasource.password=xxxx</div><div class="line">spring.datasource.type=com.alibaba.druid.pool.DruidDataSource</div><div class="line">spring.datasource.driver-class-name=com.mysql.jdbc.Driver</div><div class="line">#初始化连接大小</div><div class="line">spring.datasource.druid.initial-size=0</div><div class="line">#连接池最大使用连接数量</div><div class="line">spring.datasource.druid.max-active=20</div><div class="line">#连接池最小空闲</div><div class="line">spring.datasource.druid.min-idle=0</div><div class="line">#获取连接最大等待时间</div><div class="line">spring.datasource.druid.max-wait=6000</div><div class="line">spring.datasource.druid.validation-query=SELECT 1</div><div class="line">#spring.datasource.druid.validation-query-timeout=6000</div><div class="line">spring.datasource.druid.test-on-borrow=false</div><div class="line">spring.datasource.druid.test-on-return=false</div><div class="line">spring.datasource.druid.test-while-idle=true</div><div class="line">#配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒</div><div class="line">spring.datasource.druid.time-between-eviction-runs-millis=60000</div><div class="line">#置一个连接在池中最小生存的时间，单位是毫秒</div><div class="line">spring.datasource.druid.min-evictable-idle-time-millis=25200000</div><div class="line">#spring.datasource.druid.max-evictable-idle-time-millis=</div><div class="line">#打开removeAbandoned功能,多少时间内必须关闭连接</div><div class="line">spring.datasource.druid.removeAbandoned=true</div><div class="line">#1800秒，也就是30分钟</div><div class="line">spring.datasource.druid.remove-abandoned-timeout=1800</div><div class="line">#&lt;!-- 1800秒，也就是30分钟 --&gt;</div><div class="line">spring.datasource.druid.log-abandoned=true</div><div class="line">spring.datasource.druid.filters=mergeStat</div></pre></td></tr></table></figure>
<blockquote>
<p>在全局配置文件<code>application.properties</code>文件中配置以上的信息即可注入一个数据源到Spring Boot中。其实这仅仅是一种方式，下面介绍另外一种方式。</p>
</blockquote>
<p>在自动配置类中<code>DruidDataSourceAutoConfigure</code>中有如下一段代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span>(initMethod = <span class="string">"init"</span>)</div><div class="line">  <span class="meta">@ConditionalOnMissingBean</span></div><div class="line">  <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</div><div class="line">      LOGGER.info(<span class="string">"Init DruidDataSource"</span>);</div><div class="line">      <span class="keyword">return</span> <span class="keyword">new</span> DruidDataSourceWrapper();</div><div class="line">  &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>@ConditionalOnMissingBean</code>和<code>@Bean</code>这两个注解的结合，意味着我们可以覆盖，只需要提前在<code>IOC</code>中注入一个<code>DataSource</code>类型的<code>Bean</code>即可。</p>
</blockquote>
<p>因此我们在自定义的配置类中定义如下配置即可：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">     * <span class="doctag">@Bean</span>：向IOC容器中注入一个Bean</div><div class="line">     * <span class="doctag">@ConfigurationProperties</span>：使得配置文件中以spring.datasource为前缀的属性映射到Bean的属性中</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="meta">@ConfigurationProperties</span>(prefix = <span class="string">"spring.datasource"</span>)</div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="comment">//做一些其他的自定义配置，比如密码加密等......</span></div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DruidDataSource();</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>以上介绍了两种数据源的配置方式，第一种比较简单，第二种适合扩展，按需选择。</p>
</blockquote>
<h2 id="整合Mybatis"><a href="#整合Mybatis" class="headerlink" title="整合Mybatis"></a>整合Mybatis</h2><p>Spring Boot 整合Mybatis其实很简单，简单的几步就搞定，首先添加依赖：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis.spring.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>第二步找到自动配置类<code>MybatisAutoConfiguration</code>，有如下一行代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@EnableConfigurationProperties</span>(MybatisProperties.class)</div></pre></td></tr></table></figure></p>
<blockquote>
<p>老套路了，全局配置文件中配置前缀为<code>mybatis</code>的配置将会映射到该类中的属性。</p>
</blockquote>
<p>可配置的东西很多，比如<code>XML文件的位置</code>、<code>类型处理器</code>等等，如下简单的配置：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mybatis.type-handlers-package=com.demo.typehandler</div><div class="line">mybatis.configuration.map-underscore-to-camel-case=true</div></pre></td></tr></table></figure></p>
<p>如果需要通过包扫描的方式注入Mapper，则需要在配置类上加入一个注解：<code>@MapperScan</code>，其中的value属性指定需要扫描的包。</p>
<blockquote>
<p>直接在全局配置文件配置各种属性是一种比较简单的方式，其实的任何组件的整合都有不少于两种的配置方式，下面来介绍下配置类如何配置。</p>
</blockquote>
<p><code>MybatisAutoConfiguration</code>自动配置类有如下一断代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span></div><div class="line"><span class="meta">@ConditionalOnMissingBean</span></div><div class="line"><span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactory</span><span class="params">(DataSource dataSource)</span> <span class="keyword">throws</span> Exception </span>&#123;&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>@ConditionalOnMissingBean</code>和<code>@Bean</code>真是老搭档了，意味着我们又可以覆盖，只需要在IOC容器中注入<code>SqlSessionFactory（Mybatis六剑客之一生产者）</code>。</p>
</blockquote>
<p>在自定义配置类中注入即可，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">    * 注入SqlSessionFactory</div><div class="line">    */</div><div class="line">   <span class="meta">@Bean</span>(<span class="string">"sqlSessionFactory1"</span>)</div><div class="line">   <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactory</span><span class="params">(DataSource dataSource)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">       SqlSessionFactoryBean sqlSessionFactoryBean = <span class="keyword">new</span> SqlSessionFactoryBean();</div><div class="line">       sqlSessionFactoryBean.setDataSource(dataSource);</div><div class="line">       sqlSessionFactoryBean.setMapperLocations(<span class="keyword">new</span> PathMatchingResourcePatternResolver().getResources(<span class="string">"classpath*:/mapper/**/*.xml"</span>));</div><div class="line">       org.apache.ibatis.session.Configuration configuration = <span class="keyword">new</span> org.apache.ibatis.session.Configuration();</div><div class="line">       <span class="comment">// 自动将数据库中的下划线转换为驼峰格式</span></div><div class="line">       configuration.setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</div><div class="line">       configuration.setDefaultFetchSize(<span class="number">100</span>);</div><div class="line">       configuration.setDefaultStatementTimeout(<span class="number">30</span>);</div><div class="line">       sqlSessionFactoryBean.setConfiguration(configuration);</div><div class="line">       <span class="keyword">return</span> sqlSessionFactoryBean.getObject();</div><div class="line">   &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>以上介绍了配置Mybatis的两种方式，其实在大多数场景中使用第一种已经够用了，至于为什么介绍第二种呢？当然是为了多数据源的整合而做准备了。</p>
</blockquote>
<p>在<code>MybatisAutoConfiguration</code>中有一行很重要的代码，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@ConditionalOnSingleCandidate</span>(DataSource.class)</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>@ConditionalOnSingleCandidate</code>这个注解的意思是当IOC容器中只有一个候选Bean的实例才会生效。</p>
</blockquote>
<p>这行代码标注在Mybatis的自动配置类中有何含义呢？下面介绍，哈哈哈~<br><img src="https://gitee.com/chenjiabing666/BlogImage/raw/master/Spring%20Boot%E7%AC%AC%E5%8D%81%E4%B8%89%E5%BC%B9%EF%BC%8C%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90%E6%95%B4%E5%90%88/1.jpg" alt=""></p>
<h2 id="多数据源如何整合？"><a href="#多数据源如何整合？" class="headerlink" title="多数据源如何整合？"></a>多数据源如何整合？</h2><p>上文留下的问题：为什么的Mybatis自动配置上标注如下一行代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@ConditionalOnSingleCandidate</span>(DataSource.class)</div></pre></td></tr></table></figure></p>
<blockquote>
<p>以上这行代码的言外之意：当IOC容器中只有一个数据源DataSource，这个自动配置类才会生效。</p>
</blockquote>
<p><strong>哦？照这样搞，多数据源是不能用Mybatis吗？</strong></p>
<p>可能大家会有一个误解，认为多数据源就是多个的<code>DataSource</code>并存的，当然这样说也不是不正确。</p>
<blockquote>
<p>多数据源的情况下并不是多个数据源并存的，Spring提供了<code>AbstractRoutingDataSource</code>这样一个抽象类，使得能够在多数据源的情况下任意切换，相当于一个<strong>动态路由</strong>的作用，作者称之为<code>动态数据源</code>。因此Mybatis只需要配置这个动态数据源即可。</p>
</blockquote>
<h3 id="什么是动态数据源？"><a href="#什么是动态数据源？" class="headerlink" title="什么是动态数据源？"></a>什么是动态数据源？</h3><p>动态数据源简单的说就是能够自由切换的数据源，类似于一个动态路由的感觉，Spring 提供了一个抽象类<code>AbstractRoutingDataSource</code>，这个抽象类中哟一个属性，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> Map&lt;Object, Object&gt; targetDataSources;</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>targetDataSources</code>是一个<code>Map</code>结构，所有需要切换的数据源都存放在其中，根据指定的<code>KEY</code>进行切换。当然还有一个默认的数据源。</p>
</blockquote>
<p><code>AbstractRoutingDataSource</code>这个抽象类中有一个抽象方法需要子类实现，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> Object <span class="title">determineCurrentLookupKey</span><span class="params">()</span></span>;</div></pre></td></tr></table></figure></p>
<blockquote>
<p><code>determineCurrentLookupKey()</code>这个方法的返回值决定了需要切换的数据源的<code>KEY</code>，就是根据这个<code>KEY</code>从<code>targetDataSources</code>取值（数据源）。</p>
</blockquote>
<h3 id="数据源切换如何保证线程隔离？"><a href="#数据源切换如何保证线程隔离？" class="headerlink" title="数据源切换如何保证线程隔离？"></a>数据源切换如何保证线程隔离？</h3><p>数据源属于一个公共的资源，在多线程的情况下如何保证线程隔离呢？不能我这边切换了影响其他线程的执行。</p>
<blockquote>
<p>说到线程隔离，自然会想到<code>ThreadLocal</code>了，将切换数据源的<code>KEY</code>（用于从<code>targetDataSources</code>中取值）存储在<code>ThreadLocal</code>中，执行结束之后清除即可。</p>
</blockquote>
<p>单独封装了一个<code>DataSourceHolder</code>，内部使用<code>ThreadLocal</code>隔离线程，代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 使用ThreadLocal存储切换数据源后的KEY</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataSourceHolder</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">//线程  本地环境</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;String&gt; dataSources = <span class="keyword">new</span> InheritableThreadLocal();</div><div class="line"></div><div class="line">    <span class="comment">//设置数据源</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setDataSource</span><span class="params">(String datasource)</span> </span>&#123;</div><div class="line">        dataSources.set(datasource);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">//获取数据源</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getDataSource</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> dataSources.get();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">//清除数据源</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">clearDataSource</span><span class="params">()</span> </span>&#123;</div><div class="line">        dataSources.remove();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="如何构造一个动态数据源？"><a href="#如何构造一个动态数据源？" class="headerlink" title="如何构造一个动态数据源？"></a>如何构造一个动态数据源？</h3><p>上文说过只需继承一个抽象类<code>AbstractRoutingDataSource</code>，重写其中的一个方法<code>determineCurrentLookupKey()</code>即可。代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 动态数据源，继承AbstractRoutingDataSource</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicDataSource</span> <span class="keyword">extends</span> <span class="title">AbstractRoutingDataSource</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 返回需要使用的数据源的key，将会按照这个KEY从Map获取对应的数据源（切换）</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">determineCurrentLookupKey</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">//从ThreadLocal中取出KEY</span></div><div class="line">        <span class="keyword">return</span> DataSourceHolder.getDataSource();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 构造方法填充Map，构建多数据源</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DynamicDataSource</span><span class="params">(DataSource defaultTargetDataSource, Map&lt;Object, Object&gt; targetDataSources)</span> </span>&#123;</div><div class="line">        <span class="comment">//默认的数据源，可以作为主数据源</span></div><div class="line">        <span class="keyword">super</span>.setDefaultTargetDataSource(defaultTargetDataSource);</div><div class="line">        <span class="comment">//目标数据源</span></div><div class="line">        <span class="keyword">super</span>.setTargetDataSources(targetDataSources);</div><div class="line">        <span class="comment">//执行afterPropertiesSet方法，完成属性的设置</span></div><div class="line">        <span class="keyword">super</span>.afterPropertiesSet();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>上述代码很简单，分析如下：</p>
<ol>
<li>一个多参的构造方法，指定了默认的数据源和目标数据源。</li>
<li>重写<code>determineCurrentLookupKey()</code>方法，返回数据源对应的<code>KEY</code>，这里是直接从<code>ThreadLocal</code>中取值，就是上文封装的<code>DataSourceHolder</code>。</li>
</ol>
<h3 id="定义一个注解"><a href="#定义一个注解" class="headerlink" title="定义一个注解"></a>定义一个注解</h3><p>为了操作方便且低耦合，不能每次需要切换的数据源的时候都要手动调一下接口吧，可以定义一个切换数据源的注解，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 切换数据源的注解</div><div class="line"> */</div><div class="line"><span class="meta">@Target</span>(value = ElementType.METHOD)</div><div class="line"><span class="meta">@Retention</span>(value = RetentionPolicy.RUNTIME)</div><div class="line"><span class="meta">@Documented</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> SwitchSource &#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 默认切换的数据源KEY</div><div class="line">     */</div><div class="line">    String DEFAULT_NAME = <span class="string">"hisDataSource"</span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 需要切换到数据的KEY</div><div class="line">     */</div><div class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> DEFAULT_NAME</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>注解中只有一个<code>value</code>属性，指定了需要切换数据源的<code>KEY</code>。</p>
<p>有注解还不行，当然还要有切面，代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Aspect</span></div><div class="line"><span class="comment">//优先级设置到最高</span></div><div class="line"><span class="meta">@Order</span>(Ordered.HIGHEST_PRECEDENCE)</div><div class="line"><span class="meta">@Component</span></div><div class="line"><span class="meta">@Slf</span>4j</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataSourceAspect</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Pointcut</span>(<span class="string">"@annotation(SwitchSource)"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pointcut</span><span class="params">()</span> </span>&#123;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 在方法执行之前切换到指定的数据源</div><div class="line">     * <span class="doctag">@param</span> joinPoint</div><div class="line">     */</div><div class="line">    <span class="meta">@Before</span>(value = <span class="string">"pointcut()"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">beforeOpt</span><span class="params">(JoinPoint joinPoint)</span> </span>&#123;</div><div class="line">        <span class="comment">/*因为是对注解进行切面，所以这边无需做过多判定，直接获取注解的值，进行环绕，将数据源设置成远方，然后结束后，清楚当前线程数据源*/</span></div><div class="line">        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();</div><div class="line">        SwitchSource switchSource = method.getAnnotation(SwitchSource.class);</div><div class="line">        log.info(<span class="string">"[Switch DataSource]:"</span> + switchSource.value());</div><div class="line">        DataSourceHolder.setDataSource(switchSource.value());</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 方法执行之后清除掉ThreadLocal中存储的KEY，这样动态数据源会使用默认的数据源</div><div class="line">     */</div><div class="line">    <span class="meta">@After</span>(value = <span class="string">"pointcut()"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterOpt</span><span class="params">()</span> </span>&#123;</div><div class="line">        DataSourceHolder.clearDataSource();</div><div class="line">        log.info(<span class="string">"[Switch Default DataSource]"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这个<code>ASPECT</code>很容易理解，<code>beforeOpt()</code>在方法之前执行，取值<code>@SwitchSource</code>中value属性设置到<code>ThreadLocal</code>中;<code>afterOpt()</code>方法在方法执行之后执行，清除掉<code>ThreadLocal</code>中的<code>KEY</code>，保证了如果不切换数据源，则用默认的数据源。</p>
<h3 id="如何与Mybatis整合？"><a href="#如何与Mybatis整合？" class="headerlink" title="如何与Mybatis整合？"></a>如何与Mybatis整合？</h3><p>单一数据源与Mybatis整合上文已经详细讲解了，数据源<code>DataSource</code>作为参数构建了<code>SqlSessionFactory</code>，同样的思想，只需要把这个数据源换成动态数据源即可。注入的代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">     * 创建动态数据源的SqlSessionFactory，传入的是动态数据源</div><div class="line">     * <span class="doctag">@Primary</span>这个注解很重要，如果项目中存在多个SqlSessionFactory，这个注解一定要加上</div><div class="line">     */</div><div class="line">    <span class="meta">@Primary</span></div><div class="line">    <span class="meta">@Bean</span>(<span class="string">"sqlSessionFactory2"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactoryBean</span><span class="params">(DynamicDataSource dynamicDataSource)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        SqlSessionFactoryBean sqlSessionFactoryBean = <span class="keyword">new</span> SqlSessionFactoryBean();</div><div class="line">        sqlSessionFactoryBean.setDataSource(dynamicDataSource);</div><div class="line">        org.apache.ibatis.session.Configuration configuration = <span class="keyword">new</span> org.apache.ibatis.session.Configuration();</div><div class="line">        configuration.setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</div><div class="line">        configuration.setDefaultFetchSize(<span class="number">100</span>);</div><div class="line">        configuration.setDefaultStatementTimeout(<span class="number">30</span>);</div><div class="line">        sqlSessionFactoryBean.setConfiguration(configuration);</div><div class="line">        <span class="keyword">return</span> sqlSessionFactoryBean.getObject();</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>与Mybatis整合很简单，只需要把数据源替换成自定义的动态数据源<code>DynamicDataSource</code>。</p>
</blockquote>
<p>那么动态数据源如何注入到IOC容器中呢？看上文自定义的<code>DynamicDataSource</code>构造方法，肯定需要两个数据源了，因此必须先注入两个或者多个数据源到IOC容器中，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">    * <span class="doctag">@Bean</span>：向IOC容器中注入一个Bean</div><div class="line">    * <span class="doctag">@ConfigurationProperties</span>：使得配置文件中以spring.datasource为前缀的属性映射到Bean的属性中</div><div class="line">    */</div><div class="line">   <span class="meta">@ConfigurationProperties</span>(prefix = <span class="string">"spring.datasource"</span>)</div><div class="line">   <span class="meta">@Bean</span>(<span class="string">"dataSource"</span>)</div><div class="line">   <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span></span>&#123;</div><div class="line">       <span class="keyword">return</span> <span class="keyword">new</span> DruidDataSource();</div><div class="line">   &#125;</div><div class="line"></div><div class="line">   <span class="comment">/**</span></div><div class="line">    * 向IOC容器中注入另外一个数据源</div><div class="line">    * 全局配置文件中前缀是spring.datasource.his</div><div class="line">    */</div><div class="line">   <span class="meta">@Bean</span>(name = SwitchSource.DEFAULT_NAME)</div><div class="line">   <span class="meta">@ConfigurationProperties</span>(prefix = <span class="string">"spring.datasource.his"</span>)</div><div class="line">   <span class="function"><span class="keyword">public</span> DataSource <span class="title">hisDataSource</span><span class="params">()</span> </span>&#123;</div><div class="line">       <span class="keyword">return</span> DataSourceBuilder.create().build();</div><div class="line">   &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>以上构建的两个数据源，一个是<strong>默认的数据源</strong>，一个是需要<strong>切换到的数据源（<code>targetDataSources</code>）</strong>，这样就组成了动态数据源了。数据源的一些信息，比如<code>url</code>，<code>username</code>需要自己在全局配置文件中根据指定的前缀配置即可，代码不再贴出。</p>
</blockquote>
<p>动态数据源的注入代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">     * 创建动态数据源的SqlSessionFactory，传入的是动态数据源</div><div class="line">     * <span class="doctag">@Primary</span>这个注解很重要，如果项目中存在多个SqlSessionFactory，这个注解一定要加上</div><div class="line">     */</div><div class="line">    <span class="meta">@Primary</span></div><div class="line">    <span class="meta">@Bean</span>(<span class="string">"sqlSessionFactory2"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactoryBean</span><span class="params">(DynamicDataSource dynamicDataSource)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        SqlSessionFactoryBean sqlSessionFactoryBean = <span class="keyword">new</span> SqlSessionFactoryBean();</div><div class="line">        sqlSessionFactoryBean.setDataSource(dynamicDataSource);</div><div class="line">        org.apache.ibatis.session.Configuration configuration = <span class="keyword">new</span> org.apache.ibatis.session.Configuration();</div><div class="line">        configuration.setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</div><div class="line">        configuration.setDefaultFetchSize(<span class="number">100</span>);</div><div class="line">        configuration.setDefaultStatementTimeout(<span class="number">30</span>);</div><div class="line">        sqlSessionFactoryBean.setConfiguration(configuration);</div><div class="line">        <span class="keyword">return</span> sqlSessionFactoryBean.getObject();</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>这里还有一个问题：IOC中存在多个数据源了，那么事务管理器怎么办呢？它也懵逼了，到底选择哪个数据源呢？因此事务管理器肯定还是要重新配置的。</p>
</blockquote>
<p>事务管理器此时管理的数据源将是动态数据源<code>DynamicDataSource</code>，配置如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">  * 重写事务管理器，管理动态数据源</div><div class="line">  */</div><div class="line"> <span class="meta">@Primary</span></div><div class="line"> <span class="meta">@Bean</span>(value = <span class="string">"transactionManager2"</span>)</div><div class="line"> <span class="function"><span class="keyword">public</span> PlatformTransactionManager <span class="title">annotationDrivenTransactionManager</span><span class="params">(DynamicDataSource dataSource)</span> </span>&#123;</div><div class="line">     <span class="keyword">return</span> <span class="keyword">new</span> DataSourceTransactionManager(dataSource);</div><div class="line"> &#125;</div></pre></td></tr></table></figure></p>
<p>至此，Mybatis与多数据源的整合就完成了。</p>
<h3 id="演示"><a href="#演示" class="headerlink" title="演示"></a>演示</h3><p>使用也是很简单，在需要切换数据源的方法上方标注<code>@SwitchSource</code>切换到指定的数据源即可，如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//不开启事务</span></div><div class="line"><span class="meta">@Transactional</span>(propagation = Propagation.NOT_SUPPORTED)</div><div class="line"><span class="comment">//切换到HIS的数据源</span></div><div class="line"><span class="meta">@SwitchSource</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> List&lt;DeptInfo&gt; <span class="title">list</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> hisDeptInfoMapper.listDept();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这样只要执行到这方法将会切换到<code>HIS</code>的数据源，方法执行结束之后将会清除，执行默认的数据源。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本篇文章讲了Spring Boot与单数据源、Mybatis、多数据源之间的整合，希望这篇文章能够帮助读者理解多数据源的整合，虽说用的不多，但是在有些领域仍然是比较重要的。</p>
<p>原创不易，点点赞分享一波，谢谢支持~</p>
<blockquote>
<p><strong>源码已经上传，需要源码的朋友公众号回复关键词<code>多数据源</code>。</strong></p>
</blockquote>
<p><img src="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" alt=""></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>写的可还行？</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="不才陈某 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
	<div>
	
<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/2020/10/21/SpringBoot与多数据源的那点事儿/">Spring Boot 与多数据源的那点事儿~</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 不才陈某 的个人博客">不才陈某</a></p>
  <p><span>发布时间:</span>2020年10月21日 - 16:44</p>
  <p><span>最后更新:</span>2020年10月22日 - 21:12</p>
  <p><span>原始链接:</span><a href="/2020/10/21/SpringBoot与多数据源的那点事儿/" title="Spring Boot 与多数据源的那点事儿~">https://chenjiabing666.github.io/2020/10/21/SpringBoot与多数据源的那点事儿/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://chenjiabing666.github.io/2020/10/21/SpringBoot与多数据源的那点事儿/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
</div>

  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring-Boot/" rel="tag"><i class="fa fa-tag"></i> Spring Boot</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/10/20/这类注解都不知道，还好意思说用过Spring Boot/" rel="next" title="这类注解都不知道，还好意思说用过Spring Boot~">
                <i class="fa fa-chevron-left"></i> 这类注解都不知道，还好意思说用过Spring Boot~
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="不才陈某" />
            
              <p class="site-author-name" itemprop="name">不才陈某</p>
              <p class="site-description motion-element" itemprop="description">本站是不才陈某的技术分享博客。内容涵盖Java后端技术、Spring Boot、微服务架构、系统安全、前端、系统监控等相关的研究与知识分享。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">63</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/1556564194374926" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-globe"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/xiao-ming-64-34-45" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_34162294" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" target="_blank" title="微信公众号">
                      
                        <i class="fa fa-fw fa-globe"></i>微信公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.pexels.com/zh-cn/" title="Pexels" target="_blank">Pexels</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/" title="纯洁的微笑" target="_blank">纯洁的微笑</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#写这篇文章的目的"><span class="nav-text">写这篇文章的目的</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是多数据源？"><span class="nav-text">什么是多数据源？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#何时用到多数据源？"><span class="nav-text">何时用到多数据源？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#整合单一的数据源"><span class="nav-text">整合单一的数据源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#整合Mybatis"><span class="nav-text">整合Mybatis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多数据源如何整合？"><span class="nav-text">多数据源如何整合？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是动态数据源？"><span class="nav-text">什么是动态数据源？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据源切换如何保证线程隔离？"><span class="nav-text">数据源切换如何保证线程隔离？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何构造一个动态数据源？"><span class="nav-text">如何构造一个动态数据源？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义一个注解"><span class="nav-text">定义一个注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何与Mybatis整合？"><span class="nav-text">如何与Mybatis整合？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#演示"><span class="nav-text">演示</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">不才陈某</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">143.1k</span>
  
</div>

<!--





  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共143.1k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'RtlQOgOT3M0hgyMeogykSQjT-gzGzoHsz',
        appKey: 'vSCxLU88wnXVf0Pa8mwJrCPm',
        placeholder: '原创不易，欢迎各位指正',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
